<template>
  <div class="h-20 border-t border-gray-200 bg-white px-6 py-4">
    <div class="flex items-center space-x-4">
      <!-- 录音按钮 -->
      <div class="relative">
        <el-button
          :type="props.isRecording ? 'danger' : 'primary'"
          circle
          size="large"
          @click="toggleRecording"
          :loading="props.isProcessing"
          :disabled="props.isProcessing"
          class="recording-button"
        >
          <el-icon v-if="!props.isProcessing">
            <component :is="props.isRecording ? 'VideoPause' : 'Microphone'" />
          </el-icon>
        </el-button>
        
        <!-- 录音波形动画 -->
        <div v-if="props.isRecording" class="absolute -top-8 left-1/2 transform -translate-x-1/2">
          <div class="recording-wave flex items-center space-x-1">
            <div v-for="n in 5" :key="n" class="wave-bar"></div>
          </div>
        </div>
      </div>
      
      <!-- 文本输入框 -->
      <div class="flex-1">
        <el-input
          v-model="textMessage"
          placeholder="输入消息..."
          @keyup.enter="sendTextMessage"
          :disabled="props.isProcessing"
          size="large"
        >
          <template #append>
            <el-button 
              @click="sendTextMessage"
              :disabled="!textMessage.trim() || props.isProcessing"
              type="primary"
            >
              <el-icon><Promotion /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 语音设置 -->
      <div class="flex items-center space-x-3">
        <!-- 语速控制 -->
        <el-tooltip content="语速调节">
          <div class="flex items-center space-x-2">
            <el-icon class="text-gray-500"><Bell /></el-icon>
            <el-slider
              v-model="voiceSettings.voiceSpeed"
              :min="0.5"
              :max="2.0"
              :step="0.1"
              style="width: 80px"
              @change="updateVoiceSettings"
            />
          </div>
        </el-tooltip>
        
        <!-- 自动情绪检测开关 -->
        <el-tooltip content="自动情绪检测">
          <el-switch
            v-model="voiceSettings.autoEmotionDetection"
            size="small"
            @change="updateVoiceSettings"
          />
        </el-tooltip>
        
        <!-- 显示进度面板开关 -->
        <el-tooltip content="显示语音处理进度">
          <el-switch
            v-model="showProgressPanel"
            size="small"
            @change="toggleProgressPanel"
          />
        </el-tooltip>
        
        <!-- 设置按钮 -->
        <el-tooltip content="语音设置">
          <el-button circle size="small" @click="openVoiceSettings">
            <el-icon><Setting /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>
    
    <!-- 录音状态提示 -->
    <div v-if="props.isRecording" class="text-center mt-2">
      <span class="text-sm text-blue-500">🎤 正在录音中，松开发送...</span>
    </div>
    <div v-else-if="props.isProcessing" class="text-center mt-2">
      <span class="text-sm text-gray-500">⏳ 处理中，请稍候...</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Microphone, 
  VideoPause, 
  Promotion, 
  Bell, 
  Setting 
} from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/chat'
import { blobToBase64, requestAudioPermission } from '@/utils/audio'

// Emits
const emit = defineEmits<{
  'send-text': [content: string]
  'send-voice': [audioBlob: Blob]
  'toggle-progress-panel': [show: boolean]
}>()

// Props
interface Props {
  isRecording: boolean
  isProcessing: boolean
}
const props = defineProps<Props>()

// Router and Store
const router = useRouter()
const chatStore = useChatStore()

// 响应式数据
const textMessage = ref('')
const showProgressPanel = ref(true) // 默认显示进度面板
const voiceSettings = reactive({
  voiceSpeed: 1.0,
  voicePitch: 1.0,
  autoEmotionDetection: true
})

// 录音相关
let mediaRecorder: MediaRecorder | null = null
let audioChunks: Blob[] = []
let audioStream: MediaStream | null = null

// 方法
const toggleRecording = async () => {
  if (props.isRecording) {
    stopRecording()
  } else {
    await startRecording()
  }
}

const startRecording = async () => {
  try {
    // 检查权限
    const hasPermission = await requestAudioPermission()
    if (!hasPermission) {
      ElMessage.error('无法访问麦克风，请检查权限设置')
      return
    }

    audioStream = await navigator.mediaDevices.getUserMedia({ 
      audio: {
        sampleRate: 16000,
        channelCount: 1,
        echoCancellation: true,
        noiseSuppression: true
      }
    })
    
    // 强制使用WAV格式以兼容阿里云API
    const supportedTypes = [
      'audio/wav',
      'audio/mp4',
      'audio/webm;codecs=opus',
      'audio/webm'
    ]
    
    let mimeType = 'audio/wav'
    for (const type of supportedTypes) {
      if (MediaRecorder.isTypeSupported(type)) {
        mimeType = type
        break
      }
    }
    
    // 如果浏览器不支持WAV，使用MP4作为备选
    if (mimeType === 'audio/webm' || mimeType === 'audio/webm;codecs=opus') {
      console.warn('浏览器不支持WAV格式，使用MP4格式')
      if (MediaRecorder.isTypeSupported('audio/mp4')) {
        mimeType = 'audio/mp4'
      }
    }
    
    console.log('使用的 MIME 类型:', mimeType)
    
    mediaRecorder = new MediaRecorder(audioStream, {
      mimeType: mimeType
    })
    
    audioChunks = []
    
    mediaRecorder.ondataavailable = (event) => {
      console.log('收到录音数据:', event.data.size, 'bytes')
      if (event.data.size > 0) {
        audioChunks.push(event.data)
      }
    }
    
    mediaRecorder.onerror = (event) => {
      console.error('MediaRecorder 错误:', event)
      ElMessage.error('录音过程中发生错误')
    }
    
    mediaRecorder.onstop = () => {
      if (audioChunks.length > 0) {
        // 使用 MediaRecorder 的原始 MIME 类型
        const audioBlob = new Blob(audioChunks, { type: mediaRecorder?.mimeType || 'audio/webm' })
        console.log('创建的音频Blob:', audioBlob)
        console.log('Blob类型:', audioBlob.type)
        console.log('Blob大小:', audioBlob.size)
        console.log('Blob构造函数:', audioBlob.constructor.name)
        console.log('是否为Blob实例:', audioBlob instanceof Blob)
        
        // 验证 Blob 是否有效
        if (audioBlob.size === 0) {
          console.error('创建的Blob大小为0，录音可能失败')
          ElMessage.error('录音失败，请重试')
          return
        }
        
        emit('send-voice', audioBlob)
      } else {
        console.error('没有录音数据')
        ElMessage.error('录音失败，没有录音数据')
      }
      
      // 停止所有音频轨道
      if (audioStream) {
        audioStream.getTracks().forEach(track => track.stop())
        audioStream = null
      }
    }
    
    mediaRecorder.start(100) // 每100ms收集一次数据
    chatStore.setRecordingState(true)
    
  } catch (error) {
    console.error('录音启动失败:', error)
    ElMessage.error('无法启动录音，请检查麦克风权限')
  }
}

const stopRecording = () => {
  if (mediaRecorder && mediaRecorder.state === 'recording') {
    mediaRecorder.stop()
    chatStore.setRecordingState(false)
  }
}

const sendTextMessage = () => {
  if (textMessage.value.trim()) {
    emit('send-text', textMessage.value.trim())
    textMessage.value = ''
  }
}

const updateVoiceSettings = async () => {
  try {
    await chatStore.updateVoiceSettings(voiceSettings)
  } catch (error) {
    console.error('更新语音设置失败:', error)
  }
}

const openVoiceSettings = () => {
  router.push('/voice-settings')
}

// 切换进度面板显示
const toggleProgressPanel = () => {
  emit('toggle-progress-panel', showProgressPanel.value)
}
</script>

<style scoped>
.recording-button {
  @apply relative;
}

.recording-button.is-loading {
  @apply pointer-events-none;
}

.recording-wave {
  @apply bg-red-500 text-white px-3 py-1 rounded-full text-xs flex items-center;
}

.wave-bar {
  @apply w-1 bg-white rounded-full;
  height: 4px;
  animation: wave 1s infinite ease-in-out;
}

.wave-bar:nth-child(2) { animation-delay: 0.1s; }
.wave-bar:nth-child(3) { animation-delay: 0.2s; }
.wave-bar:nth-child(4) { animation-delay: 0.3s; }
.wave-bar:nth-child(5) { animation-delay: 0.4s; }

@keyframes wave {
  0%, 40%, 100% { transform: scaleY(1); }
  20% { transform: scaleY(3); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .flex.items-center.space-x-4 {
    @apply flex-wrap space-x-2;
  }
  
  .flex.items-center.space-x-3 {
    @apply hidden;
  }
}
</style>

